import 'package:aero_frisbee/app/state/af_app_state_ext.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/home/af_home_page.dart';
import 'package:aero_frisbee/pages/modues/message/af_message_page.dart';
import 'package:aero_frisbee/pages/modues/message/pages/followed/view_model/af_followed_list_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:aero_frisbee/pages/modues/mine/af_mine_page.dart';
import 'package:aero_frisbee/pages/modues/mine/profile/af_profile_screen.dart';
import 'package:aero_frisbee/pages/modues/videos/af_video_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final tabIndexProvider = StateProvider.autoDispose<int>((ref) {
  return 0;
});

class Keys {
  static final tabKey = GlobalKey<AppTabPageState>();
}

class AppTabPage extends ConsumerStatefulWidget {
  const AppTabPage({Key? key}) : super(key: key);
  @override
  AppTabPageState createState() => AppTabPageState();
}

class AppTabPageState extends ConsumerState<AppTabPage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  late TabController _controller;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    final curIndex = ref.watch(tabIndexProvider);
    ref.listen(addFriendServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        "Follow successfully".toast(
          onDismiss: () {},
        );
        ref.invalidate(getUserInfoFutureProvider);
      }
    });
    ref.listen(blockServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getBlockListFutureProvider);
        ref.invalidate(getUserInfoFutureProvider);
        "Blocked successfully".toast(
          onDismiss: () {
            Navigator.popUntil(context, (route) => route.isFirst);
          },
        );
      }
    });
    return Scaffold(
        key: _scaffoldKey,
        resizeToAvoidBottomInset: true,
        backgroundColor: Colors.black,
        body: TabBarView(
          physics: const NeverScrollableScrollPhysics(),
          controller: _controller,
          children: const [
            AfHomePage(),
            AfVideoPage(),
            AfMessagePage(),
            AfMinePage(),
          ],
        ),
        endDrawer: const AfProfileScreen(),
        extendBody: true,
        drawerEnableOpenDragGesture: false,
        drawerEdgeDragWidth: 0,
        endDrawerEnableOpenDragGesture: false,
        bottomNavigationBar: ClipRRect(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(16),
            topRight: Radius.circular(16),
          ),
          child: Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: const Color(0xff211F1E).withAlpha(8),
                  blurRadius: 8,
                  offset: const Offset(0, -2),
                )
              ],
            ),
            child: BottomAppBar(
              elevation: 0,
              height: kBottomNavigationBarHeight,
              padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 20),
              shape: const CircularNotchedRectangle(),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  AfTabItem(
                    index: 0,
                    isSelected: curIndex == 0,
                    onTap: () {
                      scrollToTab(0);
                    },
                  ),
                  AfTabItem(
                    index: 1,
                    isSelected: curIndex == 1,
                    onTap: () {
                      scrollToTab(1);
                    },
                  ),
                  AfTabItem(
                    index: 2,
                    isSelected: curIndex == 2,
                    onTap: () {
                      scrollToTab(2);
                    },
                  ),
                  AfTabItem(
                    index: 3,
                    isSelected: curIndex == 3,
                    onTap: () {
                      scrollToTab(3);
                    },
                  ),
                ],
              ),
            ),
          ),
        ));
  }

  scrollToTab(int index) {
    _controller.animateTo(index);
    switch (index) {
      case 0:
        AFLogPvManger.stat(page: AFLogPages.tabHome);
        break;
      case 1:
        AFLogPvManger.stat(page: AFLogPages.tabFind);
        break;
      case 3:
        AFLogPvManger.stat(page: AFLogPages.tabMe);
        break;
    }
    ref.read(tabIndexProvider.notifier).state = index;
  }

  void showHomeEndDrawerPages() {
    _scaffoldKey.currentState?.openEndDrawer();
  }

  @override
  void initState() {
    _controller = TabController(
        length: 4,
        vsync: this,
        animationDuration: const Duration(milliseconds: 10));
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class AfTabItem extends StatelessWidget {
  const AfTabItem({
    Key? key,
    required this.index,
    required this.isSelected,
    this.onTap,
  }) : super(key: key);

  final int index;
  final bool isSelected;
  final Function()? onTap;

  Widget get icon {
    switch (index) {
      case 0:
        return isSelected
            ? Assets.tabs.iconTabSelectedHome.image(width: 30)
            : Assets.tabs.iconTabUnselectedHome.image(width: 30);
      case 1:
        return isSelected
            ? Assets.tabs.iconTabSelectedVideo.image(width: 30)
            : Assets.tabs.iconTabUnselectedVideo.image(width: 30);
      case 2:
        return isSelected
            ? Assets.tabs.iconTabSelectedMsg.image(width: 30)
            : Assets.tabs.iconTabUnselectedMsg.image(width: 30);
      default:
        return isSelected
            ? Assets.tabs.iconTabSelectedMine.image(width: 30)
            : Assets.tabs.iconTabUnselectedMine.image(width: 30);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(child: icon),
        ),
      ),
    );
  }
}
